from celery import Celery
from django.conf import settings
from django.core.mail import send_mail
from django.template import loader
import os
import django
import time
from celery import shared_task



os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'electronice.settings')
django.setup()
from db.models import Goods
import random
from django_redis import get_redis_connection

# 创建一个实例对象
app = Celery('celery_tasks.tasks', broker='redis://www.ccpython.cn:6379/2')  # (‘路径’， broker)


@app.task
def send_register_active_email(to_email, username, token):
    """定义任务函数,发送激活邮件"""
    subject = '光华商贸会员注册信息'  # 邮件的主题
    message = ''  # 邮件正文，会被html_message覆盖
    from_email = settings.EMAIL_FROM  # 邮件的发件人
    reciever = [to_email]  # 收件人列表
    html_message = '<h1>{}，888欢迎注册</h1> <p>请点击以下链接完成账号激活<a href="http://127.0.0.1:8000/login/login_activate/{}">http://127.0.0.1:8000/login/login_activate/{}</a></p>'.format(
        username, token, token)  # 按照html文档规则解析内容
    send_mail(subject, message, from_email, reciever, html_message=html_message)  # 发送邮件
    # 为了体现出celery异步完成发送邮件，这里睡眠5秒
    time.sleep(6)


@app.task
def generate_static_index_html():
    """
    生成页面静态化
    """
    boy = Goods.objects.filter(goodstype_id=1, status=1).values()
    boys = random.sample(list(boy), 8)
    # 女装
    girl = Goods.objects.filter(goodstype_id=2, status=1).values()
    girls = random.sample(list(girl), 8)
    # 童装
    kid = Goods.objects.filter(goodstype_id=3, status=1).values()
    kids = random.sample(list(kid), 8)
    # 包包
    bag = Goods.objects.filter(goodstype_id=4, status=1).values()
    bags = random.sample(list(bag), 8)
    # 鞋靴
    shoe = Goods.objects.filter(goodstype_id=5, status=1).values()
    shoes = random.sample(list(shoe), 8)
    # 爆款(每次随机3个)
    a = random.sample(list(girl), 3)
    b = random.sample(list(boy), 3)
    context = {
        'boys': boys,
               'girls': girls,
               'kids': kids,
               'bags': bags,
               'shoes': shoes,
               'a': a, 'b': b
               }

    # 1.加载模板文件
    template = loader.get_template('goods/static_index.html')

    # 2.渲染模板内容（数据填坑）
    html_data = template.render(context)

    # 3.生成首页静态文件
    file_path = os.path.join(settings.GENERATED_STATIC_HTML_FILES_DIR, 'static/index.html')# 生成首页静态文件的路径
    with open(file_path, 'w', encoding="utf-8") as f:
        f.write(html_data)

